﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using System.IO;

namespace ServerUpload
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

        void Button_Click(object sender, RoutedEventArgs e)
        {
                // Create a new PDF document
                PdfDocument document = new PdfDocument();

                // Create an empty page
                PdfPage page = document.AddPage();
                //page.Contents.CreateSingleContent().Stream.UnfilteredValue;

                // Get an XGraphics object for drawing
                XGraphics gfx = XGraphics.FromPdfPage(page);

                XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always);

                // Create a font
                XFont font = new XFont("Arial", 20, XFontStyle.Bold, options);

                // Draw the text
                gfx.DrawString(text1.Text, font, XBrushes.Black,
                  new XRect(0, 0, page.Width, page.Height),
                  XStringFormats.Center);

                
                var stream = new MemoryStream();
                document.Save(stream);

                // Save the document...
                UploadFile("filename.pdf", stream);
                //document.Save(d.OpenFile());
            
        }

        public void UploadFile(string fileName, Stream data)
        {
            UriBuilder ub = new UriBuilder("http://localhost:49834/Receiver.ashx");
            ub.Query = string.Format("filename={0}", fileName);

            WebClient c = new WebClient();
            
            c.OpenWriteCompleted += (sender, e) =>
            {
                PushData(data, e.Result);
                e.Result.Close();
                data.Close();
            };
            c.OpenWriteAsync(ub.Uri);
            

        }

        private void PushData(Stream input, Stream output)
        {
            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
            {
                output.Write(buffer, 0, bytesRead);
            }
        }

    }
}
